// $Id: loggercountrequesthtl.cpp 65 2004-10-27 21:44:50Z hansemil $
#include "loggercountrequesthtl.h"
#include "loghandler.h"
#include "node.h"
#include "noderequestfileparameters.h"
#include <iostream>
#include <list>
#include <vector>
using namespace std;

/**
 * Init members and register apropriate listeners at the log handler.
 */
LoggerCountRequestHTL::LoggerCountRequestHTL()
	: 	m_sizeListSum(0), m_failedCount(0)
{
	LogHandler::getInstance()->addLogger(this, "clock_tick");
	LogHandler::getInstance()->addLogger(this, "node_routeFile");
}

/**
 * Opens file for writing and stores the Eos pointer
 */
void LoggerCountRequestHTL::eos_simulate_start(void *eos)
{
	openFile(&m_fout, "countrequesthtl.csv");
	m_fout << "Time Step, Average, Minimum, First Quartile, Median, Third Quartile, Maximum, Successful Request Count, Failed Request Count" << endl;

	m_eos = (Eos *)eos;
}

/**
 * Closes file
 */
void LoggerCountRequestHTL::eos_simulate_stop(void *eos)
{
	m_fout.close();
}

/**
 * Writes the statistics for each tick
 */
void LoggerCountRequestHTL::clock_tick(unsigned int time)
{
	// Write time step
	m_fout << time;

	// Write statistics
	writeCountStats(m_fout, m_sizeList, m_sizeListSum);
	m_fout << "," << m_failedCount;

	// Write end
	m_fout << endl;

	// Clear variables for next timestep
	m_sizeList.clear();
	m_sizeListSum = 0;
	m_failedCount = 0;
}

/**
 * Checks if a request call is a final success or final fail and saves it for writing on tick
 */
void LoggerCountRequestHTL::node_routeFile(void *thisNode, void *requestor, void *params_in, unsigned char result)
{
	NodeRequestFileParameters *params = (NodeRequestFileParameters *)params_in;
	// Check that it's not a insert
	if(!params->m_insert){
		// Final success
		if(!result && thisNode==params->m_fileOwner){
			m_sizeListSum += params->m_hopCount;
			m_sizeList.push_back(params->m_hopCount);
		}
		// Final fail
		else if(result && thisNode == requestor){
			m_failedCount++;
		}
	}
}
